package com.tiancikeji.zaoke.app.dao.food.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.tiancikeji.zaoke.app.dao.food.FoodImageDao;
import com.tiancikeji.zaoke.app.model.food.FoodImage;

public class FoodImageDaoImpl extends JdbcDaoSupport implements FoodImageDao{

	private static final String TABLE = "`zaoke`.`food_image`";
	private static final String QUERY_VIEW = "`id`, `food_id`, `url`, `add_userid`, `add_time`, `lastmod_userid`, `lastmod_time`, `type`";

	public List<FoodImage> getAllImages() {
		String sql = "select " + QUERY_VIEW + " from " + TABLE;
		return _query(sql);
	}

	public List<FoodImage> getImagesByFoodIds(Set<Long> remainings) {
		String sql = "select " + QUERY_VIEW + " from " + TABLE + " where `food_id` in (";
		sql += StringUtils.join(remainings, ",");
		sql += ")";
		return _query(sql);
	}

	private List<FoodImage> _query(String sql) {
		List<FoodImage> images = getJdbcTemplate().query(sql, new RowMapper<FoodImage>() {

			public FoodImage mapRow(ResultSet rs, int rowNum) throws SQLException {
				FoodImage image = new FoodImage();
				image.setId(rs.getLong("id"));
				image.setFoodid(rs.getLong("food_id"));
				image.setUrl(rs.getString("url"));
				image.setAddUserid(rs.getLong("add_userid"));
				image.setAddTime(rs.getDate("add_time"));
				image.setLastmodUserid(rs.getLong("lastmod_userid"));
				image.setLastmodTime(rs.getDate("lastmod_time"));
				image.setType(rs.getInt("type"));
				return image;
			}
		});
		return images;
	}
}
